// @ts-ignore
import { Effect, Reducer, Subscription, request } from 'umi';

export interface RankModelState {
  toplist: [];
  topId: string;
  listData: any;
}

export interface RankModelType {
  namespace: 'rank';
  state: RankModelState;
  effects: any;
  reducers: any;
  subscriptions: any;
}

const rankModel: RankModelType = {
  namespace: 'rank',

  state: {
    toplist: [],
    topId: '',
    listData: null,
  },

  effects: {
    *getToplist({ type, payload }: any, { put, call, select }: any) {
      let data = yield request('/toplist');
      let obj = {
        toplist: data.list,
      };
      yield put({
        type: 'saveToplist',
        payload: obj,
      });
    },
    *getListData({ type, payload }: any, { put, call, select }: any) {
      let data = yield request('/top/list?id=' + payload.id);
      yield put({
        type: 'saveListData',
        payload: {
          listData: data.playlist,
        },
      });
    },
  },
  reducers: {
    saveToplist(state: any, action: any) {
      return {
        ...state,
        ...action.payload,
      };
    },
    changeTopId(state: any, action: any) {
      return {
        ...state,
        ...action.payload,
      };
    },
    saveListData(state: any, action: any) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }: any) {
      return history.listen(({ pathname, query }: any) => {
        if (pathname === '/rank') {
          if (query.topId) {
            dispatch({
              type: 'changeTopId',
              payload: {
                topId: query.topId,
              },
            });
          } else {
            let data = request('/toplist');
            data.then((res: any) => {
              dispatch({
                type: 'changeTopId',
                payload: {
                  topId: res.list[0].id,
                },
              });
            });
          }
        }
      });
    },
  },
};

export default rankModel;
